package ms.shop.controller;

import com.alibaba.fastjson.JSONObject;
import ms.common.util.excel.ExcelClient;
import org.apache.catalina.User;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Project Name: ms
 * File Name: TestController
 * Package Name: ms.shop.controller
 * Date: 2018/6/8  15:37
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@RestController
public class TestController {

    @PostMapping("/upload")
    public void upload(@RequestParam MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();

        ExcelClient<TestUser> excelClient = new ExcelClient<>();
        List<TestUser> list = excelClient.parseExcel(TestUser.class, inputStream, fileName);
        list.forEach(testUser -> {
            System.out.println(JSONObject.toJSONString(testUser));
        });
    }

    @RequestMapping("/down")
    public void down(HttpServletResponse resp) throws IOException {
        List<TestUser> list = new ArrayList<>();
        TestUser testUser = new TestUser();
        testUser.setId(1L);
        testUser.setName("韩梅梅");
        testUser.setAge(3);
        testUser.setGender(1);
        testUser.setBirthday("2018-03-21");
        testUser.setAddress("北京");
        testUser.setTel("123123213");

        TestUser testUser1 = new TestUser();
        testUser1.setId(1L);
        testUser1.setName("韩梅梅");
        testUser1.setAge(3);
        testUser1.setGender(1);
        testUser1.setBirthday("2018-03-21");
        testUser1.setAddress("北京");
        testUser1.setTel("123123213");

        list.add(testUser);
        list.add(testUser1);

        List<String> title = new ArrayList<>();
        title.add("id");
        title.add("姓名");
        title.add("年龄");
        title.add("性别");
        title.add("生日");
        title.add("地址");
        title.add("电话");


        ExcelClient<TestUser> excelClient = new ExcelClient<>();
        HSSFWorkbook workbook = excelClient.beanToWorkbook(list, "哈哈哈", title, null, null);

        resp.setContentType("application/vnd.ms-excel");
        resp.setHeader("Content-disposition", "attachment;filename=student.xls");
        OutputStream ouputStream = resp.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }
}